/*********************************************************************************
 *      Copyright:  (C) 2022 xiezongyi<1764417007@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  mosquitto_callback_sub.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(08/05/22)
 *         Author:  xiezongyi <1764417007@qq.com>
 *      ChangeLog:  1, Release initial version on "08/05/22 16:01:29"
 *                 
 ********************************************************************************/

#include <stdio.h>
#include <stdlib.h>

#include "mosquitto.h"
#include "mosquitto_conf.h"

#define Qos			2
#define KEEPALIVE	60

void on_connect_sub(struct mosquitto *mosq, void *obj, int rc)
{
	int			ret = -1;
	mqtt_ctx_t	*mqtt = (mqtt_ctx_t *)obj;

	if(!rc)
	{
		ret = mosquitto_subscribe(mosq, NULL, mqtt->subtopic, Qos);
		if(MOSQ_ERR_SUCCESS != ret)
		{
			printf("mosquitto_subscribe() failure!\n");
			exit(1);
		}
		printf("mosquitto_subscribe() OK!\n");
	}
}

void on_disconnect_sub(struct mosquitto *mosq, void *obj, int rc)
{
	int			ret = -1;
	mqtt_ctx_t	*mqtt = (mqtt_ctx_t *)obj;

	if(!rc)
	{
		printf("Mosquitto get disconnect with server!\n");

		ret = mosquitto_connect(mosq, mqtt->hostname, mqtt->port, KEEPALIVE);
		if(MOSQ_ERR_SUCCESS != ret)
		{
			printf("Mosquitto connect with server failure!\n");
			exit(1);
		}
	}
}

//在代理响应订阅发送SUBACK时调用回调
void on_subscribe(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos)
{
	printf("Subcribe %d topic successfully!\n", qos_count);	
}

//当客户端收到消息时调用该回调
void on_message_sub(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message)
{
	//打印有效载荷
	printf("topic=%s, Qos=%d, payload=%s\n", message->topic, message->qos, (char *)message->payload);
}
